﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Net;
using Soft.Net;

namespace Soft.Service
{

    /// <summary>
    /// 发送服务在线广播
    /// </summary>
    public class SendServiceOnlineBroadcast : ErrorResponse
    {
        public SendServiceOnlineBroadcast()
        {
            this.Broadcast.Error += this.OnError;

            //定时器定时执行
            this.mTimer.Elapsed += delegate (object s, ElapsedEventArgs e)
            {
                this.Broadcast.Send(this.mUdpBroadcastItem);
            };
        }


        ~SendServiceOnlineBroadcast()
        {
            this.Stop();
            this.Broadcast.Dispose();
        }


        public IP ListeningIP { get; set; } = IP.Empty;


        public void Start()
        {
            string str = (this.ListeningIP == IP.Empty) ? ToolsClass.GetFirstInterNetworkIPAddress(Dns.GetHostEntry(Dns.GetHostName()).AddressList).ToString() : this.ListeningIP.Text;
            //开启广播功能
            this.Broadcast.Start();
            //设置广播数据
            this.mUdpBroadcastItem = new UdpBroadcastItem(UdpBroadcastFlag.JobServiceOnline);
            this.mUdpBroadcastItem.SetData(this.InstanceName + "|" + str);
            //发送广播数据
            this.Broadcast.Send(this.mUdpBroadcastItem);
            this.mTimer.Interval = 2000.0;
            this.mTimer.Start();
        }

        public void Hold()
        {
            this.mTimer.Interval = 60000.0;
        }

        public void Stop()
        {
            this.mTimer.Stop();
            this.Broadcast.Stop();
        }

        public string InstanceName { get; set; } = "SoftJOBSERVICE";

        private const double INTERVAL_MILLISECONDS_FOR_STANDARD_SPEEED = 2000.0;

        private const double INTERVAL_MILLISECONDS_FOR_LOW_SPEED = 60000.0;

        private Timer mTimer = new Timer(2000.0);

        private UdpBroadcastItem mUdpBroadcastItem;

        /// <summary>
        /// 发送Udp广播
        /// </summary>
        private ServiceInfoSendBroadcast Broadcast = new ServiceInfoSendBroadcast();


    }
}
